<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="盘点单号">
          <el-input
            v-model="searchParam.orderNo"
            placeholder="请输入盘点单号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="仓库编码">
          <el-input
            v-model="searchParam.warehouseCode"
            placeholder="请输入仓库编码"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="仓位编码">
          <el-input
            v-model="searchParam.binCode"
            placeholder="请输入仓位编码"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="盘点日期">
          <el-date-picker
            v-model="searchParam.inventoryDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getinventoryDate"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-input
            v-model="searchParam.status"
            placeholder="请输入状态"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="deleteBatch()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChangeHandle"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="盘点单号"
          prop="orderNo"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="任务名称"
          prop="orderName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="仓库名称"
          prop="warehouseName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="仓位名称"
          prop="binName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="盘点日期"
          prop="inventoryDate"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="盘点开始时间"
          prop="inventoryBeginTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="盘点结束时间"
          prop="inventoryEndTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="状态"
          prop="status"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ row }">
            <el-tag v-if="row.status == 1" type="warning">{{
              useDictionary("InventoryState", row.status)
            }}</el-tag>
            <el-tag v-if="row.status == 2">{{
              useDictionary("InventoryState", row.status)
            }}</el-tag>
            <el-tag v-if="row.status == 3" type="success">{{
              useDictionary("InventoryState", row.status)
            }}</el-tag>
            <el-tag v-if="row.status == 4" type="danger">{{
              useDictionary("InventoryState", row.status)
            }}</el-tag>
            <el-tag v-if="row.status == 5" type="info">{{
              useDictionary("InventoryState", row.status)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建人名"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="280">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 1"
              type="primary"
              size="small"
              link
              @click="startInventoryTask(scope.row.id)"
              ><i-ep-open />
              开始盘点
            </el-button>
            <el-button
              link
              v-if="scope.row.status === 3 || scope.row.status === 5"
              @click="openInventoryDialog(scope.row)"
              type="primary"
              plain
              ><i-ep-DocumentCopy />查看盘点表</el-button
            >
            <el-button
              v-if="scope.row.status === 2"
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-select />
              盘点完成
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-if="scope.row.status === 1"
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <wmsinventorytask-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <inventoryCollectionnew
      :visible="inventoryDialog.visible"
      :title="inventoryDialog.title"
      :data="inventoryDialog.data"
      @change-visible="changeInventoryVisible"
    />
<!--    <inventoryDifferencenew-->
<!--      :visible="inventoryDifferenceDialog.visible"-->
<!--      :title="inventoryDifferenceDialog.title"-->
<!--      :data="inventoryDifferenceDialog.data"-->
<!--      @reset-table="(id: string) => (id?.length ? getTableList() : reset())"-->
<!--      @change-visible="changeInventoryDifferenceVisible"-->
<!--    />-->
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { ElMessage } from "element-plus";

defineOptions({
  name: "WMSWMSINVENTORYTASK",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/wms/inventoryTask/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  orderNo: "",
  warehouseCode: "",
  binCode: "",
  status: "",
};

const deleteParam = {
  api: "/wms/inventoryTask/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  selections,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/wms/inventoryTask/get/${id}`,
    method: "get",
  })
    .then((data) => {
      console.log("getInfo response data:", data);
      console.log("data.data:", data.data);
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

function deleteBatch() {
  if (ids.value.length === 0) {
    ElMessage.warning("请选择要删除的记录！");
    return;
  }

  if (selections.value.length > 0 && selections.value[0].status !== 1) {
    ElMessage.warning("只能删除状态为未开始的记录！");
    return;
  }

  // 调用单个删除方法
  deleteItem(ids.value[0]);
}

/** 打开盘点任务表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改盘点任务";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增盘点任务";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开盘点任务表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "盘点任务详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/wms/inventoryTask/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

/**
 * 开始盘点
 */
function startInventoryTask(id: String) {
  ElMessageBox.confirm("确定开始盘点吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: "/wms/inventoryTask/startInventoryTask",
      method: "post",
      data: id,
    });
  });
}
function getinventoryDate(data: any) {
  if (data) {
    searchParam.value.inventoryDateStart = data[0];
    searchParam.value.inventoryDateEnd = data[1];
  } else {
    searchParam.value.inventoryDateStart = "";
    searchParam.value.inventoryDateEnd = "";
  }
}

const dataTableRef = ref();
const handleSelectionChangeHandle = async (selection) => {
  if (selection.length > 1) {
    const lastSelect = selection[selection.length - 1];
    dataTableRef.value!.clearSelection();
    dataTableRef.value!.toggleRowSelection(lastSelect, true);
  } else {
    selections.value = selection;
    ids.value = selection.map((item: any) => item.id);
  }
};

const inventoryDifferenceDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

function changeInventoryDifferenceVisible(value: boolean) {
  inventoryDifferenceDialog.visible = value;
  if (!value) {
    inventoryDifferenceDialog.data = {};
  }
}

/** 打开盘信息弹窗 */
function openInventoryDifferenceDialog() {
  var rows = dataTableRef.value.getSelectionRows();

  inventoryDifferenceDialog.title = "盘点差异";
  inventoryDifferenceDialog.visible = true;

  inventoryDifferenceDialog.data = {
    // movementTypeCode: formData.movementTypeCode,
    inventoryTaskId: rows[0].id,
  };
}
const inventoryDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

function changeInventoryVisible(value: boolean) {
  inventoryDialog.visible = value;
  if (!value) {
    inventoryDialog.data = {};
  }
}

function openInventoryDialog(row: any) {
  inventoryDialog.title = "盘点清单";
  inventoryDialog.visible = true;
  inventoryDialog.data = {
    taskId: row.id,
  };
}
</script>
